Class Computer
public abstract class Computer {
public abstract String getRAM();
public abstract String getHDD();
public abstract String getCPU();
@Override
public String toString(){
return "RAM= "+this.getRAM()+", HDD="+this.getHDD()+", CPU="+this.getCPU();
}
}
Class ComputerFactory
public class ComputerFactory {
public static Computer getComputer(String type, String ram, String hdd, String cpu)
{ if("PC".equalsIgnoreCase(type))
return new PC(ram, hdd, cpu);
else if("Server".equalsIgnoreCase(type)) return new Server(ram, hdd, cpu);
return null;
}
}
Class PC
public class PC extends Computer {
private String ram;
private String hdd;
private String cpu;
public PC(String ram, String hdd, String cpu){
this.ram=ram;
this.hdd=hdd;
this.cpu=cpu;
}
@Override
public String getRAM() {
return this.ram;
}
@Override
public String getHDD() {
return this.hdd;
}
@Override
public String getCPU() {
return this.cpu;
}
}
Class Server
public class Server extends Computer {
private String ram;
private String hdd;
private String cpu;
public Server(String ram, String hdd, String cpu){
this.ram=ram;
this.hdd=hdd;
this.cpu=cpu;
}
@Override
public String getRAM() {
return this.ram;
}
@Override
public String getHDD() {
return this.hdd;
}
@Override
public String getCPU() {
return this.cpu;
}
}
Class SingletonComputerFactory
public class SingletonComputerFactory {
private static SingletonComputerFactory singletonFactory;
// SingletonExample prevents any other class from instantiating
private SingletonComputerFactory() {
}
// Providing Global point of access
public static SingletonComputerFactory getSingletonFactory() {
if (null == singletonFactory) {
singletonFactory = new SingletonComputerFactory();
}
return singletonFactory;
}
public Computer getComputer(String type, String ram, String hdd, String cpu)
{ if("PC".equalsIgnoreCase(type))
return new PC(ram, hdd, cpu);
else if("Server".equalsIgnoreCase(type))
return new Server(ram, hdd, cpu);
return null;
}
}
Class TestFactory (Using Singleton)
public class TestFactory {
public static void main(String[] args) {
SingletonComputerFactory fc = SingletonComputerFactory.getSingletonFactory();
Computer pc = fc.getComputer("pc","2 GB","500 GB","2.4 GHz");
Computer server = fc.getComputer("server","16 GB","1 TB","2.9 GHz");
System.out.println("Factory PC Config::"+pc);
System.out.println("Factory Server Config::"+server);
}
}
Run time output
Factory PC Config::RAM= 2 GB, HDD=500 GB, CPU=2.4 GHz
Factory Server Config::RAM= 16 GB, HDD=1 TB, CPU=2.9 GHz